import Vue from "vue";
import Vuex from "vuex";
import *as permissApi from "@/api/permission"
// 引入递归路由的方法
import recursionRoutes from "@/utils/recursionRoutes"
// 引入项目所以的路由
import router from "@/router"
import allRoutes from "@/router/generateRoutes"
// 引入动态路由
import dynamicRoutes from "@/router/dynamicRoutes"

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    userMenu: [],
    userInfo: {}, //用户信息
    currentProduct: {},//当前充值的产品对象
  },
  getters: {},
  mutations: {
    SET_MENULIST(state,payload){
      state.userMenu =[...payload];
      let target=dynamicRoutes.find(route=>route.path==="/")
      target.children=[...payload]
      // 动态的将路由添加到routes
      router.addRoute(target)
    }
  },
  actions: {
    // 请求菜单数据，根据菜单数据
    // 计算出用户的菜单
    // 计算出当前这个角色(role)的合法路由
   async FETCH_MENULIST(context, payload) {

     return permissApi.getMenuList().then(res => {
        // console.log(res);
        // 得到后端返回的菜单数据
        let{menuList}=res.data;
        // 调用recursionRoutes
        let userRoutes = recursionRoutes(allRoutes[0].children, menuList)
        // console.log(allRoutes)
        context.commit('SET_MENULIST',userRoutes)
        // console.log(userRoutes)
      })
    }
  },
  modules: {},
});
